package sistemioperativi.prodcons.sample;

import java.util.concurrent.Semaphore;

public class BufferSem extends Buffer {

	private Semaphore ciSonoElementi = new Semaphore(0);
	private Semaphore ciSonoPostiVuoti;
	private Semaphore mutex = new Semaphore(1);
	
	
	public BufferSem(int dimensione){
		super(dimensione);
		ciSonoPostiVuoti = new Semaphore(dimensione);
	}
	
	private void stampaStato() {
		System.out.print("in = " + in + " -> [");
		for (int i = 0; i < buffer.length; i++) {
			if (buffer[i] == null) {
				System.out.print(" |");
			} else {
				System.out.print("X|");
			}
		}
		System.out.println("] -> out = " + out);
	}

	
	
	@Override
	public void put(Elemento e) throws InterruptedException {
		
		ciSonoPostiVuoti.acquire();
		mutex.acquire();
		System.out.println(Thread.currentThread().getId()+" PUT di "+e.getValore());
		
		buffer[in] = e;
		in = (in + 1)%buffer.length;
		mutex.release();
		stampaStato();
		ciSonoElementi.release();
	
	}

	@Override
	public Elemento get() throws InterruptedException {
		
		ciSonoElementi.acquire();
		mutex.acquire();
		Elemento e = buffer[out];
		System.out.println(Thread.currentThread().getId()+" GET di "+e.getValore());
		out = (out + 1)%buffer.length;
		System.out.println("Posizione corrente... "+out);
		mutex.release();
		stampaStato();
		ciSonoPostiVuoti.release();
		return e;
	
	}// EO Get.
	
	
	public static void main (String []args){
		
		int dim = 10;
		Buffer buffer = new BufferSem(dim);
		int numProduttori = 4;
		int numConsumatori = 16;
		
		buffer.test(numProduttori, numConsumatori);
	}
	
	

}
